import axios from "axios";
import { ElMessage } from "element-plus";
import store from "@/store";
import { getLocal } from "@/assets/js/funcs";

// 创建axios实例
const request = axios.create({
    baseURL: "/api", // API的基础URL，实际开发中应替换为真实的API地址
    timeout: 15000, // 请求超时时间
    headers: {
        "Content-Type": "application/json;charset=utf-8",
    },
});

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        // 从本地存储获取用户令牌
        const userInfo = getLocal("gdepUserInfo");
        if (userInfo && userInfo.token) {
            config.headers["Authorization"] = `Bearer ${userInfo.token}`;
        }
        return config;
    },
    (error) => {
        console.error("请求错误", error);
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        const res = response.data;
        // 这里的判断标准需要根据实际API的返回格式调整
        if (res.code !== 200 && res.code !== 0) {
            ElMessage({
                message: res.message || "请求错误",
                type: "error",
                duration: 3000,
            });

            // 401: 未登录或Token过期
            if (res.code === 401) {
                store.commit("setLogout");
                ElMessage({
                    message: "登录已过期，请重新登录",
                    type: "warning",
                    duration: 3000,
                });
                setTimeout(() => {
                    window.location.href = "/login";
                }, 1500);
            }
            return Promise.reject(new Error(res.message || "请求错误"));
        } else {
            return res;
        }
    },
    (error) => {
        console.error("响应错误", error);
        ElMessage({
            message: error.message || "网络异常，请稍后再试",
            type: "error",
            duration: 3000,
        });
        return Promise.reject(error);
    }
);

export default request;
